const Controller = require('egg').Controller

class OrderController extends Controller {
  // 新增订单
  async add() {
    const params = this.ctx.request.body
    // 开启事务
    let transaction = await this.ctx.model.transaction()
    try {
      // 插入订单表
      let res = await this.service.order.add(
        {
          user_id: this.ctx.user.id
        },
        transaction
      )
      // 查询商品详细
      let ids = params.goods.map((item) => item.id)
      let goods_res = await this.service.goods.list({ ids })
      // 将实际购买的商品数量插入
      for (let item of goods_res) {
        for (let subItem of params.goods) {
          if (subItem.id == item.id) {
            item.goods_num = subItem.num
          }
        }
      }
      // 插入订单子表
      await this.service.order.addItem(
        {
          order_id: res.id,
          goods: goods_res
        },
        transaction
      )
      // 清库存
      await this.service.goods.clearStock({ goods: goods_res }, transaction)
      // 扣款
      const balance_res = await this.service.user.payment(
        {
          goods: goods_res,
          user_id: this.ctx.user.id
        },
        transaction
      )
      this.ctx.session.user.balance = balance_res.balance
      await transaction.commit()
      this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
    } catch (e) {
      await transaction.rollback()
      console.error(e)
      this.ctx.body = this.ctx.returnStatus.EXCEPTION(e)
    }
  }
  // 获取商品列表
  async list() {
    const params = this.ctx.query
    let res = await this.service.goods.list({
      ...params
    })
    this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
  }
  // 添加购物车
  async addCart() {
    const params = this.ctx.request.body
    let res = await this.service.goods.addCart({
      ...params,
      user_id: this.ctx.user.id
    })
    this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
  }
  // 获取购物车
  async getCart() {
    const params = this.ctx.query
    let res = await this.service.goods.getCart({
      ...params,
      user_id: this.ctx.user.id
    })
    this.ctx.body = this.ctx.returnStatus.SUCCESS(res)
  }
}

module.exports = OrderController
